package com.eystar.pdc.controller;

import com.eystar.ext.kit.UUIDKit;
import com.eystar.ext.kit.page.PageKit;
import com.eystar.ext.kit.page.PageOrder;
import com.eystar.ext.route.ControllerBind;
import com.eystar.pdc.aop.auth.AuthAnno;
import com.eystar.pdc.aop.auth.AuthAnno.AuthType;
import com.eystar.pdc.aop.log.LogAnno;
import com.eystar.pdc.aop.log.LogAnno.LogType;
import com.eystar.pdc.model.Role;
import com.eystar.pdc.model.User;
import com.eystar.pdc.util.LoginUtil;
import com.jfinal.plugin.activerecord.Page;

/**
 * 用户管理
 * @author Administrator
 *
 */
@ControllerBind(controllerKey = "/user", viewPath = "/pdc")
@AuthAnno(type = AuthType.Super, res = "user")
public class UserController extends BaseController {
	
	/**
	 * 列表展示页面
	 * @throws Exception
	 */
	@AuthAnno(auth="look")
	@LogAnno(desc = "查看用户列表", type = LogType.SEARCH)
	public void index() throws Exception{
		render("user_list.html");
	}
	
	/**
	 * 分页查找
	 * @throws Exception
	 */
	public void page() throws Exception{
		PageOrder order = new PageOrder(getParaToInt("page"), getParaToInt("rows"));
		Page<User> page = User.dao.paginate(order, getModel(User.class));
		renderJson(PageKit.toJSON(page));
	}
	
	/**
	 * 跳转到添加页面
	 * @throws Exception
	 */
	@AuthAnno(auth="save")
	public void add() throws Exception{
		setAttr("roles", Role.dao.findNormalRoles());
		render("user_form.html");
	}
	
	/**
	 * 点击保存按钮
	 * @throws Exception
	 */
	@AuthAnno(auth="save")
	@LogAnno(desc = "添加用户${user.user_name}", type = LogType.SAVE)
	public void save() throws Exception{
		User user = getSaveModel(User.class);
		user.set("user_salt", UUIDKit.nextShortUUID());
		user.set("user_pass", LoginUtil.getSaltPassword("111111", user.getSalt()));
		user.save();
		renderJson(ok());
	}
	
	/**
	 * 跳转到修改页面
	 * @throws Exception
	 */
	@AuthAnno(auth="update")
	public void edit() throws Exception{
		setAttr("user", User.dao.findById(getPara()));
		setAttr("roles", Role.dao.findNormalRoles());
		render("user_form.html");
	}
	
	/**
	 * 点击修改按钮
	 * @throws Exception
	 */
	@AuthAnno(auth="update")
	@LogAnno(desc = "修改用户${user.user_name}", type = LogType.UPDATE)
	public void update() throws Exception{
		User user = getModel(User.class);
		user.update();
		renderJson(ok());
	}
	
	/**
	 * 支持多个删除，以英文逗号隔开
	 * @throws Exception
	 */
	@AuthAnno(auth="delete")
	@LogAnno(desc = "删除用户", type = LogType.DELETE)
	public void delete() throws Exception{
		User.dao.deleteByIds(getPara("ids"));
		renderJson(ok());
	}

}